package org.yaukie.auth.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.yaukie.auth.constant.AuthCons.UserStatus;
import org.yaukie.auth.entity.LoginUser;
import org.yaukie.base.core.entity.XUser;
import org.yaukie.base.core.entity.XUserExample;
import org.yaukie.base.core.service.api.XUserService;
import org.yaukie.base.exception.UserDefinedException;
import org.yaukie.base.util.MessageTools;
import org.yaukie.base.util.StringTools;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailServiceImpl.class);
    @Autowired
    private XUserService xUserService;

    public UserDetailServiceImpl() {
    }

    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        XUserExample xUserExample = new XUserExample();
        xUserExample.createCriteria().andUserNameEqualTo(userName);
        XUser xUser = (XUser)this.xUserService.selectFirstExample(xUserExample);
        if (StringTools.isNull(xUser)) {
            log.info("当前用户：{} 不存在.", userName);
            throw new UserDefinedException(MessageTools.message("yaukie.user.not.exists", new Object[0]));
        } else if (UserStatus.DELETED.getCode().equals(xUser.getDelFlag())) {
            log.info("当前用户：{} 已被删除.", userName);
            throw new UserDefinedException("对不起，您的账号：" + userName + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(xUser.getStatus())) {
            log.info("当前用户：{} 已被停用.", userName);
            throw new UserDefinedException("对不起，您的账号：" + userName + " 已停用");
        } else {
            return this.createLoginUser(xUser);
        }
    }

    private UserDetails createLoginUser(XUser xUser) {
        LoginUser loginUser = new LoginUser();
        loginUser.setXUser(xUser);
        return loginUser;
    }
}
